//
//  ACQRResultController.m
//  MonitoringSystem
//
//  Created by JiaKang.Zhong on 16/5/9.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "ACQRResultController.h"
#import "ACQRDeviceModel.h"
#import "UtilToolsClass.h"
#import "UIImage+Extension.h"
#import "NetRequestClass.h"
#import "ACCustomButton.h"
#import "ACChangeDeviceNameController.h"
#import "SMPageControl.h"
#import "NetRequestClass.h"
#import "ACDeviceDetailModel.h"
#import "UtilToolsClass.h"
#import "UIImageView+WebCache.h"
#import "ACCustomAlertView.h"
#import "ACCustomPortButton.h"
@interface ACQRResultController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIActionSheetDelegate,UIScrollViewDelegate,UIAlertViewDelegate>{
    BOOL isFirstUploadPic;// 判断是否上传过照片
    CGRect  popPanBtnFrame;// 面板弹出的位置
    CGFloat topViewHeight;// 顶部的高度
    UIButton * preSelect;// 当前选中的按钮;
    UIButton * oldPanSelectBtn;// 面板选中的按钮
    NSString * deviceType;// 设备类型
}
/*
        约束部分
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *p12And24Constraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *p24And36Constraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *p12AndViewLeftConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pMoreAndViewRightConstraint;
/**
 *  翻译
 */
@property (weak, nonatomic) IBOutlet UILabel *cdeviceCode;
@property (weak, nonatomic) IBOutlet UILabel *cdeviceType;
@property (weak, nonatomic) IBOutlet UILabel *cdeviceNickName;
@property (weak, nonatomic) IBOutlet UILabel *cdeviceSIM;
@property (weak, nonatomic) IBOutlet UIButton *btnAddDevice;// 添加按钮

@property(nonatomic,strong) IBOutlet UILabel* lblDeviceType; // 设备类型
@property (weak, nonatomic) IBOutlet UILabel *lblCard; // SIM卡号
@property (weak, nonatomic) IBOutlet UILabel *lblIMEI; // IMEI码
@property (weak, nonatomic) IBOutlet ACCustomButton *lblDeviceNiceName; // 设备昵称
@property (weak, nonatomic) IBOutlet ACCustomPortButton *p12Btn;
@property (weak, nonatomic) IBOutlet ACCustomPortButton *p24Btn;
@property (weak, nonatomic) IBOutlet ACCustomPortButton *p36Btn;
@property (weak, nonatomic) IBOutlet UIButton *pMoreBtn;
@property (weak, nonatomic) IBOutlet UILabel *pMoreLable;
@property(nonatomic,strong) NSMutableArray* arrMutable;// 图片数组，
@property(nonatomic,weak) UIImageView * popImageView; // 点击更多弹出
@property(nonatomic,weak) UIPageControl * pageController;// 页面下标
@property (weak, nonatomic)  UIScrollView *deviceImageViews; // 顶部的设备图片
@property(nonatomic,strong) SMPageControl * pageControl; // 图片的小标选择器
@property(nonatomic,weak) UIButton * delegateButton;// 删除照片的按钮

@property(nonatomic,weak)  UIBarButtonItem* rightPhotoItem;
@property(nonatomic,weak) UIButton * addDevicePicDefaultBtn;// 添加设备照片的默认按钮
@property(nonatomic,strong) ACDeviceDetailModel * deviceDetailModel;
/*
    方法回调
 */
-(IBAction)changeDeviceNameCallBack:(id)sender;
- (IBAction)btnCountClick:(id)sender; // 端口层数的选择
- (IBAction)bindingDeviceClick:(id)sender; // 绑定设备
@end

@implementation ACQRResultController

- (NSMutableArray *)arrMutable{
    if(!_arrMutable){
        _arrMutable = [NSMutableArray array];
    }
    return _arrMutable;
}
- (instancetype)initWithModel:(ACQRDeviceModel *)qrmodel{
    if (self = [super init]) {
        self.QRModel = qrmodel;
    }
    return self;
}

// 删除图片的垃圾桶按钮
- (UIButton *)delegateButton{
    if (!_delegateButton) {
        UIButton * tempDelegateBtn = [[UIButton alloc] init];
        [tempDelegateBtn setImage:[UIImage imageNamed:@"icon-del-pic"] forState:UIControlStateNormal];
        tempDelegateBtn.frame = CGRectMake( SCREEN_WIDTH - 40, topViewHeight - 40,30,30);
        [tempDelegateBtn addTarget:self action:@selector(degelatePic) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:tempDelegateBtn];
        _delegateButton = tempDelegateBtn;
    }
    return _delegateButton;
}

// 添加第一张图
- (UIButton *)addDevicePicDefaultBtn{
    if (!_addDevicePicDefaultBtn) {
        UIButton * addFirstPic = [UIButton buttonWithType:UIButtonTypeCustom];
        addFirstPic.frame = CGRectMake(0, 0, SCREEN_WIDTH, topViewHeight);
        [addFirstPic addTarget:self action:@selector(addPictureClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:addFirstPic];
        _addDevicePicDefaultBtn = addFirstPic;
    }
    return _addDevicePicDefaultBtn;
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.modalPresentationCapturesStatusBarAppearance = YES;
    
    isFirstUploadPic = true;
    self.lblDeviceNiceName.tag = 0; // 用以区分判断
    topViewHeight = SCREEN_HEIGHT * 0.5 - 20;
     self.view.backgroundColor = ACCommentColor;
    // 从二维码扫描界面进来
    if (self.enterWithQR) {
        [self enterQRResultWithScanQR];
    }else{
   // 设备列表界面进来----- 重新获取数据
        [self requestData];
    }
    [self translateLanguage];
}

/**
 *  国际化
 */
- (void) translateLanguage{
    self.title = NSLocalizedString(@"设备信息", nil);
    self.cdeviceCode.text = NSLocalizedString(@"设备编号", nil);
    self.cdeviceType.text = NSLocalizedString(@"设备类型", nil);
    self.cdeviceSIM.text = NSLocalizedString(@"SIM卡号", nil);
    self.cdeviceNickName.text = NSLocalizedString(@"设备昵称", nil);
    [self.btnAddDevice setTitle:NSLocalizedString(@"添加", nil) forState:UIControlStateNormal];

    [self.lblDeviceNiceName setTitle:NSLocalizedString(@"点击添加设备昵称", nil) forState:UIControlStateNormal];
    [self.p12Btn setTitle:[NSString stringWithFormat:@"12%@",NSLocalizedString(@"点", nil)] forState:UIControlStateNormal];
    [self.p24Btn setTitle:[NSString stringWithFormat:@"24%@",NSLocalizedString(@"点", nil)] forState:UIControlStateNormal];
    [self.p36Btn setTitle:[NSString stringWithFormat:@"36%@",NSLocalizedString(@"点", nil)] forState:UIControlStateNormal];
}


#pragma mark 从二维码扫描进进入  --- 判断是否是当前设备存不存在管理者
- (void) enterQRResultWithScanQR{
    deviceType = self.QRModel.type;
    /*   初始化约束    */
    [self initConstraint];
    /*   初始化UI    */
    [self initUI];
    if(!self.QRModel.isEmployer && self.QRModel.employer.length){     // 如果是初次绑定设备 在默认图片区域加个按钮
            self.navigationItem.rightBarButtonItem = nil;
        self.lblDeviceNiceName.userInteractionEnabled = NO;
    }
    if ([[UD objectForKey:@"maskLayerGuid1-1"] intValue]) { // true隐藏，false 显示
        self.navigationItem.hidesBackButton = YES;
    }
    [self.arrMutable removeAllObjects];
    // 有照片的情况，添加删除按钮
    if (self.QRModel.img_url.count > 0) {
        // 显示图片
        for ( int index = 0; index < self.QRModel.img_url.count; index ++) {
            UIImageView * tempImage = [[UIImageView alloc] initWithFrame:CGRectMake(index * SCREEN_WIDTH, 0, SCREEN_WIDTH, topViewHeight)];
            tempImage.contentMode = UIViewContentModeScaleAspectFill;
            [tempImage sd_setImageWithURL:[NSURL URLWithString:[USER_DEVICE_IMAGE_URL stringByAppendingFormat:@"/%@",self.QRModel.img_url[index]]] placeholderImage:[UIImage imageNamed:@"zanwutupian"]];
            [self.arrMutable addObject:tempImage];
            [self.deviceImageViews addSubview:tempImage];
        }
        self.deviceImageViews.contentSize = CGSizeMake(self.QRModel.img_url.count * SCREEN_WIDTH, topViewHeight);
        // 创建指示下标 --- 默认
        [self loadPageControlWithTotalPage:self.arrMutable.count and:0];
        // 添加照片
        if (self.QRModel.employer.length && self.QRModel.isEmployer) {
            [self.view bringSubviewToFront:self.delegateButton];
        }
    }else{
        // 添加照片按钮
        if (self.QRModel.isEmployer || self.QRModel.employer.length == 0) {
            [self.view bringSubviewToFront:self.addDevicePicDefaultBtn];
        }
    }
    // 没有管理者--默认选中12，存在管理者，选中管理员配置方案
    [self enableDevicePort:self.QRModel.number];
    self.lblDeviceType.text = self.QRModel.type;
    self.lblIMEI.text = self.QRModel.imei;
    self.lblCard.text = self.QRModel.card;
    NSString * nickName = self.QRModel.nickName;
    if ([nickName isEqualToString:@""]) {
        nickName = @"点击添加设备昵称";
        [self.lblDeviceNiceName setTitle:NSLocalizedString(nickName,nil) forState:UIControlStateNormal];
    }else{
        [self.lblDeviceNiceName setTitle:nickName forState:UIControlStateNormal];
    }
    
}



#pragma mark  从设备列表点击头像进入  ----  请求数据
- (void) requestData{
    [[UtilToolsClass getUtilTools] addDoLoading];
    __weak typeof(self) weakSelf = self;
    [NetRequestClass requestWithUrlForGetDeviceMessage:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/queryDeviceDetails.asp"] andParam:@{@"i_imei":self.i_imei} success:^(ACDeviceDetailModel *result) {
       [[UtilToolsClass getUtilTools] removeDoLoading];
        [weakSelf loadingDeviceInfo:result];
    } failure:^(NSString *failure) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
        [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
    }];
}



- (void)loadingDeviceInfo:(ACDeviceDetailModel *)result{
    self.deviceDetailModel = result;
    [self.btnAddDevice setTitle:NSLocalizedString(@"保存",nil) forState:UIControlStateNormal];
    deviceType = result.type;
    /*   初始化约束    */
    [self initConstraint];
    /*   初始化UI    */
    [self initUI];
    self.lblDeviceType.text = result.type;
    self.lblIMEI.text = result.code;
    self.lblCard.text = result.card;
    // 设备昵称
    self.lblDeviceNiceName.tag = 1;
    [self.lblDeviceNiceName setTitle:result.nickName forState:UIControlStateNormal];
    /**
     *  如果当前用户不是管理员，那么就去除掉上传照片的默认按钮，摄像机按钮，垃圾桶按钮
        禁止保存按钮
     */
    if(!self.deviceDetailModel.isEmployer){
        self.navigationItem.rightBarButtonItem = nil;
        self.lblDeviceNiceName.userInteractionEnabled = NO;
        self.btnAddDevice.enabled = NO;
    }
    [self.arrMutable removeAllObjects];
    if (result.img_url.count > 0) {
        // 显示图片
        for ( int index = 0; index < result.img_url.count; index ++) {
            UIImageView * tempImage = [[UIImageView alloc] initWithFrame:CGRectMake(index * SCREEN_WIDTH, 0, SCREEN_WIDTH, topViewHeight)];
            tempImage.contentMode = UIViewContentModeScaleAspectFill;
            [tempImage sd_setImageWithURL:[NSURL URLWithString:[USER_DEVICE_IMAGE_URL stringByAppendingFormat:@"/%@",result.img_url[index]]] placeholderImage:[UIImage imageNamed:@"zanwutupian"]];
            [self.arrMutable addObject:tempImage];
            [self.deviceImageViews addSubview:tempImage];
        }
        self.deviceImageViews.contentSize = CGSizeMake(result.img_url.count * SCREEN_WIDTH, topViewHeight);
        // 创建指示下标 --- 默认
        [self loadPageControlWithTotalPage:self.arrMutable.count and:0];
        // 添加照片垃圾桶按钮
        if (self.deviceDetailModel.isEmployer) {
            [self.view bringSubviewToFront:self.delegateButton];
        }
    }else{
        // 添加照片中间区域的默认按钮
        if (self.deviceDetailModel.isEmployer) {
            [self.view bringSubviewToFront:self.addDevicePicDefaultBtn];
        }
    }
    // 当前选中的按
    [self enableDevicePort:[result.number intValue]];
}


- (void) enableDevicePort:(NSInteger) portCount{
    preSelect.selected = NO;
    if (portCount == 12) {
        self.p12Btn.selected = YES;
        [self.p12Btn setImage:[UIImage imageNamed:@"icon-gou-on"] forState:UIControlStateNormal];
        preSelect = self.p12Btn;
    }else if (portCount == 24){
        self.p24Btn.selected = YES;
        [self.p24Btn setImage:[UIImage imageNamed:@"icon-gou-on"] forState:UIControlStateNormal];
        preSelect = self.p24Btn;
    }else if ( portCount == 36){
        self.p36Btn.selected = YES;
        [self.p36Btn setImage:[UIImage imageNamed:@"icon-gou-on"] forState:UIControlStateNormal];
        preSelect = self.p36Btn;
    }
}


#pragma mark  显示UI界面
- (void) initUI{

     //头部导航条背景隐藏，按钮不隐藏
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsCompact];
    self.navigationController.navigationBar.translucent = YES;
 
    //此处使底部线条颜色为红色
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    [navigationBar setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage createImageWithColor:[UIColor colorWithRed:108/255.0 green:112/255.0 blue:112/255.0 alpha:1]]];
    // 返回按钮
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"qr-back-bg"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick)];
    self.navigationItem.leftBarButtonItem = backIetm;
    self.navigationItem.hidesBackButton = YES;
    
    // 右边按钮
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"qr-photo-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(addPictureClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.rightPhotoItem = rightItem;
    // 默认图
    UIScrollView *deviceImageViews = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, topViewHeight)];
    deviceImageViews.showsVerticalScrollIndicator = NO;
    deviceImageViews.showsHorizontalScrollIndicator = NO;
    deviceImageViews.pagingEnabled = YES;
    deviceImageViews.bounces = YES;
    deviceImageViews.tag = 1;
    deviceImageViews.delegate = self;
    [self.view addSubview:deviceImageViews];
    self.deviceImageViews = deviceImageViews;

    UIImageView * imageView = [[UIImageView alloc] initWithFrame:self.deviceImageViews.frame];
    imageView.image = [UIImage imageNamed:@"zanwutupian"];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.deviceImageViews addSubview:imageView];
    self.deviceImageViews.contentSize = CGSizeMake(self.arrMutable.count * SCREEN_WIDTH,  self.deviceImageViews.frame.size.height);
}



#pragma mark 动态加载下标指示器
- (void)loadPageControlWithTotalPage:(NSInteger)tPage and:(NSInteger)cPage{
    if (self.pageControl) {
        [self.pageControl removeFromSuperview];
    }
    if (tPage <= 0 || cPage < 0) {
        return;
    }
    SMPageControl *spacePageControl = [[SMPageControl alloc] initWithTotalPage:tPage andWithCurrentPage:cPage andWithNormalImage:[UIImage imageNamed:@"qr-Forn-off"] andWithSelectImage:[UIImage imageNamed:@"qr-Forn-on"]];
    spacePageControl.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 50 , self.deviceImageViews.frame.size.height - 20, 100, 30);
    [self.view addSubview:spacePageControl];
    self.pageControl = spacePageControl;
    
}
// 约束 ----- 分两种，一种是AC3的，一种是AC2
- (void) initConstraint{
    if (SCREEN_HEIGHT == 568) {
        // 4.0
        if ([deviceType isEqualToString:@"AC3"]) {
            self.p12And24Constraint.constant = self.p12And24Constraint.constant - 20;
            self.p24And36Constraint.constant = self.p24And36Constraint.constant - 20;
            self.p12AndViewLeftConstraint.constant = self.p12AndViewLeftConstraint.constant - 5;
        }else  if ([deviceType isEqualToString:@"AC2"]) {
            self.pMoreBtn.hidden = YES;
            self.pMoreLable.hidden = YES;
            self.p12AndViewLeftConstraint.constant = self.p12AndViewLeftConstraint.constant +  5;
            self.p12And24Constraint.constant = self.p12And24Constraint.constant + 10;
            self.p24And36Constraint.constant = self.p24And36Constraint.constant + 10;
        }
    }
    if (SCREEN_HEIGHT == 667){
        // 4.7
        if ([deviceType isEqualToString:@"AC3"]) {
            self.p12And24Constraint.constant = self.p12And24Constraint.constant - 5;
            self.p24And36Constraint.constant = self.p24And36Constraint.constant - 5;
        }
        if ([deviceType isEqualToString:@"AC2"]) {
            self.p12AndViewLeftConstraint.constant = self.p12AndViewLeftConstraint.constant +  10;
            self.p12And24Constraint.constant = self.p12And24Constraint.constant + 25;
            self.p24And36Constraint.constant = self.p24And36Constraint.constant + 25;
            self.pMoreBtn.hidden = YES;
            self.pMoreLable.hidden = YES;
        }
    }else if (SCREEN_HEIGHT == 736){
        // 5.5
        if ([deviceType isEqualToString:@"AC3"]) {
            self.p12And24Constraint.constant = self.p12And24Constraint.constant + 5;
            self.p24And36Constraint.constant = self.p24And36Constraint.constant + 5;
        }
        if ([deviceType isEqualToString:@"AC2"]) {
            self.p12AndViewLeftConstraint.constant = self.p12AndViewLeftConstraint.constant +  10;
            self.p12And24Constraint.constant = self.p12And24Constraint.constant + 44;
            self.p24And36Constraint.constant = self.p24And36Constraint.constant + 44;
            self.pMoreBtn.hidden = YES;
            self.pMoreLable.hidden = YES;
        }
    }
}


-(void)backItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma  mark  *******  添加照片 *******
- (void)addPictureClick {
    if (self.arrMutable.count >= 4) {
      [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"很抱歉，照片数量已达上限",nil)];
        self.rightPhotoItem.enabled = YES;
        return;
    }
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"选择照片", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet addButtonWithTitle:NSLocalizedString(@"从相册中选择",nil)];
    [actionSheet addButtonWithTitle:NSLocalizedString(@"拍照",nil)];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
    }else if(buttonIndex == 1){
        [self getMediaFromSource:UIImagePickerControllerSourceTypePhotoLibrary];
    }else if(buttonIndex == 2){
        [self getMediaFromSource:UIImagePickerControllerSourceTypeCamera];
        
    }else{}
}


- (void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType
{
    NSArray *mediatypes=[UIImagePickerController availableMediaTypesForSourceType:sourceType];
    if([UIImagePickerController isSourceTypeAvailable:sourceType] &&[mediatypes count]>0)
    {
        NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.mediaTypes = mediatypes;
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        NSString *requiredmediatype = (NSString *)kUTTypeImage;
        NSArray *arrmediatypes = [NSArray arrayWithObject:requiredmediatype];
        [picker setMediaTypes:arrmediatypes];
        [self presentViewController:picker animated:YES completion:nil];
    }else {
        [self showOkayCancelAlert:@"当前设备不支持拍摄功能"  message:@""];
    }
}


- (void)showOkayCancelAlert:(NSString *)title message:(NSString *)message{
    NSString *otherButtonTitle = NSLocalizedString(@"确定", nil);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
    }];
    [alertController addAction:otherAction];
}


- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取修改后的图片,并进行数据压缩
    UIImage *editedImg = info[UIImagePickerControllerEditedImage];
    [self loadingImageForView:editedImg];
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 移除添加那妞
    [self.addDevicePicDefaultBtn removeFromSuperview];
    self.addDevicePicDefaultBtn = nil;
}

- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma   ********************** 显示照片 **********************
- (void) loadingImageForView:(UIImage *) img {
 
    UIImageView * newImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.arrMutable.count * SCREEN_WIDTH, 0, SCREEN_WIDTH, self.deviceImageViews.frame.size.height)];
    newImageView.contentMode = UIViewContentModeScaleAspectFill;
    newImageView.image = img;
    [self.deviceImageViews addSubview:newImageView];
     [self.arrMutable addObject:newImageView];
    self.deviceImageViews.contentSize = CGSizeMake(self.arrMutable.count * SCREEN_WIDTH,  self.deviceImageViews.frame.size.height);
    // 添加照片
    [self.view bringSubviewToFront:self.delegateButton];
    // 创建指示下标
    [self loadPageControlWithTotalPage:self.arrMutable.count and:self.arrMutable.count - 1];
    // 滚动到指定的位置
    [self.deviceImageViews setContentOffset:CGPointMake(SCREEN_WIDTH * (self.arrMutable.count  - 1), 0) animated:YES];
}


#pragma  mark 删除照片
- (void) degelatePic{
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"删除该照片?", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    alertView.tag = 0;
    [alertView show];

}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 0) {
        if (buttonIndex == 1) {
            UIImageView * tempView = self.arrMutable[self.pageControl.currentPage];
            [tempView removeFromSuperview];
            if (self.arrMutable.count == 1  ) {
                // 只有一张图片，显示默认图并且移除删除按钮
                [self.delegateButton removeFromSuperview];
                self.delegateButton = nil;
                // 加入添加图片的按钮
                [self.view bringSubviewToFront:self.addDevicePicDefaultBtn];
            }else{
                if (self.pageControl.currentPage < self.arrMutable.count) {
                    // 后面还有图片，要往前面挪动
                    for (int index =  (int)self.pageControl.currentPage + 1 ; index < self.arrMutable.count ; index ++) {
                        UIImageView * preImageView = [self.arrMutable objectAtIndex: index];
                        preImageView.frame = CGRectMake( preImageView.origin.x - SCREEN_WIDTH, 0, SCREEN_WIDTH, topViewHeight);
                    }
                }
            }
            [self.arrMutable removeObject:tempView];
            // 重新整合scrollview的滚动范围
            self.deviceImageViews.contentSize = CGSizeMake(self.arrMutable.count * SCREEN_WIDTH,  self.deviceImageViews.frame.size.height);
            // 创建指示下标
            [self loadPageControlWithTotalPage:self.arrMutable.count and:self.arrMutable.count - 1];
            self.rightPhotoItem.enabled = YES;
        }
    }else if (alertView.tag == 1){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.tag == 1){
        NSInteger index = fabs(scrollView.contentOffset.x) / scrollView.frame.size.width;
        [self.pageControl setCurrentPage:index];
    }
}


#pragma mark  选择端口数 ----------- 必填选项 -----------------
/**
 *  修改端口数前，需要判定当前的用户是否是管理员，如果是，那么就可以修改，反之就弹框提示。
 *  1.先判断设备是否存在管理者
    2.在判断当前用户是不是该管理者
     --- 是 ---允许更改
     --- 不是 --- 不允许更改，弹框提示
 */
- (IBAction)btnCountClick:(UIButton *)sender {
    if (self.QRModel.employer.length ) {
        if(!self.QRModel.isEmployer){
            //存在管理者 UIAlertView
            ACCustomAlertView * alertView = [[ACCustomAlertView alloc] initAlertViewWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.5 - 80, SCREEN_WIDTH * 0.8, 160) andSuperView:self.view];
            [alertView createTitle:NSLocalizedString(@"提示",nil) message:[NSString stringWithFormat:@"%@:+%@ %@%@",NSLocalizedString(@"该设备已被",nil),self.QRModel.zone,self.QRModel.employer,NSLocalizedString(@"用户绑定",nil)] calcelButton:@"" okButton:NSLocalizedString(@"确定",nil)];
            [[UIApplication sharedApplication].keyWindow addSubview:alertView];
            return;
        }
    }
    if ( self.deviceDetailModel.employer.length) {
        if(!self.deviceDetailModel.isEmployer){
            //存在管理者 UIAlertView
            ACCustomAlertView * alertView = [[ACCustomAlertView alloc] initAlertViewWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.5 - 80, SCREEN_WIDTH * 0.8, 160) andSuperView:self.view];
            [alertView createTitle:NSLocalizedString(@"提示",nil) message:[NSString stringWithFormat:@"%@:+%@ %@%@",NSLocalizedString(@"该设备已被",nil),self.deviceDetailModel.zone,self.deviceDetailModel.employer,NSLocalizedString(@"用户绑定",nil)] calcelButton:@"" okButton:NSLocalizedString(@"确定",nil)];
            [[UIApplication sharedApplication].keyWindow addSubview:alertView];
            return;
        }
    }
     NSInteger btnTag = sender.tag;
    popPanBtnFrame = sender.frame;
    if (self.popImageView) {
        [self.popImageView removeFromSuperview];
        self.popImageView = nil;
    }
    // AC3进入
    if (btnTag == 0) {
        [self popPanForAC3];
    }else{
      // AC2进入
            if (preSelect && preSelect.tag <= 36) {
                preSelect.selected = NO;
                 [preSelect setImage:[UIImage imageNamed:@"icon-gou-off"] forState:UIControlStateNormal];
            }else  if (preSelect && preSelect.tag > 36){
                [oldPanSelectBtn removeFromSuperview];
                self.pMoreBtn.hidden = NO;
                self.pMoreLable.hidden = NO;
                preSelect.selected = NO;
            }
            sender.selected = YES;
            [sender setImage:[UIImage imageNamed:@"icon-gou-on"] forState:UIControlStateNormal];
             preSelect = sender;
        }
}


// 弹出面板
- (void) popPanForAC3{
    CGRect targetRect = popPanBtnFrame;
    // 弹出面板
    CGFloat moreBGW = 100;
    CGFloat moreBGH = 200; 
    CGFloat moreBGX = CGRectGetMinX(targetRect) + 20;
    CGFloat moreBGY = targetRect.origin.y - moreBGH * 0.5;
    UIImageView * moreBG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qr-chooseMore-BG"]];
    moreBG.frame = CGRectMake(moreBGX, moreBGY, moreBGW, moreBGH);
    moreBG.layer.anchorPoint = CGPointMake(1,1);
    moreBG.userInteractionEnabled = YES;
    [self.view addSubview:moreBG];
    self.popImageView = moreBG;
    int indexCount = 72;
    for (int index = 0; index < 3; index ++) {
        UIButton * tempBtn = [[UIButton alloc] init];
        [tempBtn setTitle:[NSString stringWithFormat:@" %d%@",(indexCount - index * 12 ),NSLocalizedString(@"点", nil)] forState:UIControlStateNormal];
        [tempBtn setImage:[UIImage imageNamed:@"icon-gou-off"] forState:UIControlStateNormal];
        tempBtn.tag = indexCount - index * 12 ;
        CGFloat tempW = 70;
        CGFloat tempH = 27;
        CGFloat tempX = moreBG.frame.size.width * 0.5 - tempW * 0.5;
        CGFloat tempY = (moreBG.frame.size.height / 3) * index + 20 ;
        tempBtn.frame = CGRectMake(tempX, tempY, tempW, tempH);
        [tempBtn addTarget:self action:@selector(choosePortForAC3CallBack:) forControlEvents:UIControlEventTouchDown];
        [moreBG addSubview:tempBtn];
    }
}


/**
 *
 * 从更多弹出的面板中回调，选中对应的端口数.
 */
- (void) choosePortForAC3CallBack:(UIButton *)sender{

    if(preSelect && preSelect.tag <= 36){
        [preSelect setImage:[UIImage imageNamed:@"icon-gou-off"] forState:UIControlStateNormal];
        preSelect.selected = NO;
    }
    // 显示选中的端口数，隐藏更多选项
    self.pMoreBtn.hidden = YES;

    self.pMoreLable.hidden = YES;
    NSInteger objTag = sender.tag;
    if (oldPanSelectBtn) {
        [oldPanSelectBtn removeFromSuperview];
        oldPanSelectBtn = nil;
    }
    oldPanSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [oldPanSelectBtn setBackgroundImage:[UIImage imageNamed:@"btn-more-on"] forState:UIControlStateNormal];
    oldPanSelectBtn.frame = popPanBtnFrame;
    oldPanSelectBtn.tag = objTag;
    [oldPanSelectBtn setTitle:[NSString stringWithFormat:@"%d点",(int)objTag] forState:UIControlStateNormal];
    oldPanSelectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    oldPanSelectBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:oldPanSelectBtn];
    [oldPanSelectBtn addTarget:self action:@selector(popPanForAC3) forControlEvents:UIControlEventTouchDown];

    sender.selected = YES;
    preSelect = sender;
    if (self.popImageView) {
        [self.popImageView removeFromSuperview];
        self.popImageView = nil;
    }
}


#pragma mark ***********************  发送请求到服务器,绑定设备 ***********************
- (IBAction)bindingDeviceClick:(id)sender {

    [[UtilToolsClass getUtilTools] addDoLoading];
    /**/
    NSString * objStr = @"";
    for (int index = 0; index < self.arrMutable.count; index++) {
        UIImageView * tempImageView =  self.arrMutable[index];
        NSData *data = UIImageJPEGRepresentation(tempImageView.image, 0.4f);
        long length = [data length] / 1000;
        if (length > 500) {
            data = UIImageJPEGRepresentation(tempImageView.image, 0.2f);
        }
        NSString* tempStr = [data base64EncodedStringWithOptions:0];
        if (index != 0) {
             tempStr =  [NSString stringWithFormat:@";%@",tempStr];//data:image/png;base64,%
        }
       objStr =  [objStr stringByAppendingFormat:@"%@",tempStr];
    }
    NSString * tempNickName = @"";
    if (self.lblDeviceNiceName.tag == 0) {
        tempNickName = self.lblIMEI.text; // IMEI
    }else{
        tempNickName = self.lblDeviceNiceName.currentTitle;
    }
    // 转UTF-8
    NSDictionary * param = @{@"images":objStr,@"i_imei":self.lblIMEI.text,@"number":@(preSelect.tag),@"nickName":[NSString stringWithFormat:@"%@",tempNickName]};  // 第一次绑定设备
    
    NSLog(@"%@",param);
    
    __weak typeof(self) weakSelf = self;
    [[UtilToolsClass getUtilTools] addDoLoading];
    if (self.enterWithQR) {
        // 添加设备
        [NetRequestClass requestWithUrlForBindingDevice:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/deviceBinding.asp"] andParam:param success:^(NSDictionary* result) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            [weakSelf bingDeviceSuccessCallBacl:result];
            
            
          } failure:^(NSString *failure) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
        }];
    }else{
         // 修改成功
        [[UtilToolsClass getUtilTools] addDoLoading];
        [NetRequestClass requestWithUrlForUpdateDeviceInfo:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/updateDeviceDetails.asp"] andParam:param success:^(NSInteger result) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"成功", nil)];
            if (!result) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            }else if(result){
                // 没有SIM卡
                [UtilToolsClass addDisapperAlert:@"" withMessage:@"没有检测到SIM卡,修改信息失败"]; 
            }
        } failure:^(NSString *failure) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
        }];
    }
}


- (void) bingDeviceSuccessCallBacl:(NSDictionary *)resDic{
    int result = [resDic[@"result"] intValue];
    NSString * resultStr = [NSString stringWithFormat:@"%@",resDic[@"msg"]];
    if (result == 0) {
        // 设备已绑定，弹框提示，是不是新用户
        if ([resultStr isEqualToString:@"管理员"]) {
            // 新的管理员,弹框提示
            UIAlertView * alertView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示",nil) message:NSLocalizedString(@"您已成为此台设备的管理员",nil) delegate:self cancelButtonTitle:NSLocalizedString(@"确定",nil) otherButtonTitles:nil, nil];
            alertView.tag = 1;
            [alertView show];
        }else{
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    if (result == 1) {
        [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"设备已绑定",nil)];
    }
    if (result == 2) {
        // 日志表有数据，但是没有检测到该手机卡
        [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"未检测到SIM卡,请稍后重试", nil)];
    }
    if(result == 3){
        // 日志表无此台设备数据
        [UtilToolsClass addDisapperAlert:@"" withMessage:@"未检测此设备数据,请稍后重试"];
    }
}

#pragma mark   ***********************  修改昵称 ***********************
-(IBAction)changeDeviceNameCallBack:(id)sender{
    ACChangeDeviceNameController * deviceNameControlller = [[ACChangeDeviceNameController alloc] init];
    deviceNameControlller.oldName = self.lblDeviceNiceName.currentTitle;
    __weak typeof(self)weakSelf = self;
    deviceNameControlller.pushDeviceName = ^(NSString * cusDeviceName){
        if ([cusDeviceName isEqualToString:@""]) {
            self.lblDeviceNiceName.tag = 0;
            [weakSelf.lblDeviceNiceName setTitle:NSLocalizedString(@"点击添加设备昵称", nil) forState:UIControlStateNormal];
            [weakSelf.lblDeviceNiceName setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }else{
            self.lblDeviceNiceName.tag = 1;
            [weakSelf.lblDeviceNiceName setTitle:cusDeviceName forState:UIControlStateNormal];
            [weakSelf.lblDeviceNiceName setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }

    };
    // 第二种写法
//    [deviceNameControlller returnText:^(NSString *cusDeviceName) {
//       //    }];
    [self.navigationController pushViewController:deviceNameControlller animated:YES];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.popImageView) {
        [self.popImageView removeFromSuperview];
        self.popImageView = nil;
    }
}

@end
